package com.wyh.controller.gfive;

import com.wyh.common.result.FindAccountResult;
import com.wyh.common.result.Result;
import com.wyh.common.result.SysAccountManagementResult;
import com.wyh.common.utils.AccountCodeUtils;
import com.wyh.common.utils.Md5Util;
import com.wyh.domain.dto.gfive.LoginUser;
import com.wyh.domain.po.gfive.*;
import com.wyh.domain.vo.gfive.treeVo.TreeNode;
import com.wyh.domain.vo.gfive.treeVo.tree_util.DepartmentTree;
import com.wyh.domain.vo.gfive.treeVo.tree_util.DepartmentTreeUtils;
import com.wyh.domain.vo.gfive.treeVo.tree_util.ProjectRemoveNode;
import com.wyh.service.gfive.*;
import com.wyh.domain.vo.gfive.ManageProjectVo;
import com.wyh.domain.vo.gfive.UpdateAccountVo;
import com.wyh.mapper.gfivemapper.UserMapper;
import com.wyh.service.gfive.tree_service.*;
//import com.wyh.service.tree_service.*;
import io.lettuce.core.dynamic.annotation.Param;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
 * 系统管理——>账号管理
 */


@RestController
@Slf4j
@Api(tags = "系统管理-账号管理")
@RequestMapping("AccountManagement")
public class SysAccountManagementController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserMapper userMapper;

    @Resource
    private ManageProjectService manageProjectService;
    @Resource
    private IBuildingUnitsVOService iBuildingUnitsVOService;
    @Resource
    private ILayerVOService iLayerVOService;
    @Resource
    private IOrganizationVOService iOrganizationVOService;
    @Resource
    private IProjectVOService iProjectVOService;
    @Resource
    private IRoomVOService iRoomVOService;
    @Resource
    private DepartmentTreeUtils departmentTreeUtils;


    /*
     *
     * 系统管理-账号管理->分页查询所有的账户
     * @param pageHelper
     * @return

     */

    @PostMapping("/findAll")
    @ApiOperation(value = "分页查询所有的账户")
    public List<SysAccountManagementResult> findAll(@RequestBody PageHelper pageHelper) {
        List<SysAccountManagementResult> all = userService.findAll(pageHelper);
        return all;
    }
    /*
     *
     * 重置密码

     */

    @GetMapping ("/resetPassword")
    @ApiOperation(value = "重置密码")
    public Result resetPassword(@Param("id") int id) {
        User user = new User();
        user.setId(id);
        String tel = userService.selectUserTelephoneById(id);
        if (tel == null) {
            log.info("重置密码失败----未找到用户信息");
            return Result.error("没有查找到该用户信息");
        }
        user.setPassword(Md5Util.getMD5String(tel.substring(5, 11)));
        int i = userService.resetPassword(user);
        if (i == 1) {
            log.info("重置密码成功");
            return Result.success();
        } else {
            log.info("重置密码失败，未知错误");
            return Result.error("重置密码失败，未知错误");
        }
    }
    /*
     *
     * 展示系统所有正常状态的角色信息(id和name)

     */

    @GetMapping("/ShowAllRole")
    @ApiOperation(value = "展示系统的所有正常的角色信息(id和name)")
    public Result showAllRole() {
        return Result.success(roleService.showAllRole());
    }
    /*
     *
     * 新增账号

     */

    @PostMapping("/saveAccount")
    @ApiOperation(value = "新增账号")
    @Transactional
    public Result saveAccount(@RequestBody SaveAccount saveAccount) {
        if (saveAccount != null) {
//        1.新建对象
            User user = new User();
            List<UserRole> userRole = new ArrayList<>();

//        2.判断输入合法性
            String telephone = saveAccount.getTelephone();
            if (telephone.length() != 11 || telephone.charAt(0) != '1') {
                return Result.error("请检查输入手机号是否有误");
            }
            if (saveAccount.getName() == null || saveAccount.getName().equals(" ")) {
                return Result.error("姓名不能为空！");
            }

//        3.telephone设置
            user.setTelephone(saveAccount.getTelephone());

//        4.给对象赋值（pad,account,telephone另外处理）
            user.setName(saveAccount.getName());
            user.setState(1);
            user.setOrganizationid(saveAccount.getOrganizationid());

            User userId = userService.findUserId(user);
            if (userId != null) {
                return Result.error("该手机号已在系统存在");
            }

//        5.account设置
            List<User> accounts = userService.findAccountByOrganization(saveAccount.getOrganizationid());

            //获取user表中已有的账号并存入accountList
            List<String> accountList = new ArrayList<>();
            for (User a : accounts) {
                if (a != null) {
                    accountList.add(a.getAccount());
                }
            }

            if (!accountList.isEmpty()) {
                String lastAccount = accountList.get(accountList.size() - 1);
                if (lastAccount.length() >= 4) {
                    String lastFourDigits = lastAccount.substring(lastAccount.length() - 4);
                    int maxAccountNumber = 0;
                    try {
                        maxAccountNumber = Integer.parseInt(lastFourDigits);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    int nextAccountNumber = maxAccountNumber;
                    String nextAccountNumberStr = String.format("%04d", nextAccountNumber);
                    String OrName = organizationService.findOrganizationNameById(saveAccount.getOrganizationid());
                    AccountCodeUtils accountCodeUtils = new AccountCodeUtils(OrName, nextAccountNumberStr);
                    user.setAccount(accountCodeUtils.generateNewAccount());
                } else {
                    return Result.error("帐户格式无效");
                }
            } else {
                String newAccount = organizationService.findOrganizationNameById(saveAccount.getOrganizationid());
                AccountCodeUtils accountCodeUtils1 = new AccountCodeUtils(newAccount, "0000");
                user.setAccount(accountCodeUtils1.getCompanyAbbreviation() + "0000");
            }

//        6.pad设置
            String substring = saveAccount.getTelephone().substring(5, 11);
            user.setPassword(Md5Util.getMD5String(substring));

//        7.判断传入角色是否系统拥有
            List<String> integers = roleService.selectRolesByIds(saveAccount.getRoleid());
            if (integers.size() < saveAccount.getRoleid().length) {
                return Result.error("传入数据中，有角色信息不存在");
            }

//        8.添加用户
            int i = userService.saveAccount(user);
            if (i > 0) {
                log.info("添加账号成功");

//        9.用户新增成功后，根据组织信息和电话号码，来锁定当前用户的id,增加用户角色表数据
                User user1 = userService.findUserId(user);

                for (int i1 = 0; i1 < saveAccount.getRoleid().length; i1++) {
                    UserRole userRole1 = new UserRole();
                    userRole1.setUserid(user1.getId());
                    userRole1.setRoleid(saveAccount.getRoleid()[i1]);
                    userRole1.setState(1);
                    userRole.add(i1, userRole1);
                }
                int i1 = userRoleService.saveUserRole(userRole);
                if (i1 > 0) {
                    log.info("用户角色增加成功");
                    return Result.success("用户增加成功");
                } else {
                    log.info("用户角色增加失败");
                    return Result.error("用户增加失败");
                }
            }
        }
        return Result.error();
    }
    /**
     * 根据条件查找账号
     */
    @PostMapping("/selectAccount")
    @ApiOperation(value = "根据条件查询分页展示账号")
    public Result selectAccount(@RequestBody FindAccountResult findAccountResult){
//        SysAccountManagementResult sysAccountManagementResult = new SysAccountManagementResult();
//        sysAccountManagementResult.setAccount(findAccountResult.getAccount());
//        sysAccountManagementResult.setName(findAccountResult.getName());
//        sysAccountManagementResult.setId(findAccountResult.getId());
//        sysAccountManagementResult.setRoleid(findAccountResult.getRoleid());
//        sysAccountManagementResult.setOrganizationid(findAccountResult.getOrganizationid());
//        sysAccountManagementResult.setState(findAccountResult.getState());
//        sysAccountManagementResult.setTelephone(findAccountResult.getTelephone());
//        PageHelper pageHelper =new PageHelper();
//        pageHelper.setCurrentPage(findAccountResult.getCurrentPage());
//        pageHelper.setPageSize(findAccountResult.getPageSize());
        List<FindAccountResult> users = userService.findUsers(findAccountResult);
        return Result.success(users, (long) users.size());
    }
    /**
     * 编辑账户
     */
    @PostMapping("/updateUser")
    @ApiOperation(value = "编辑账户")
    @Transactional
    public Result updateUser(@RequestBody UpdateAccountVo updateAccountVo){
        if (updateAccountVo != null) {
//        1.查找对象
            User user = userService.findById(updateAccountVo.getId());
            User user1 = new User();
            List<UserRole> userRole = new ArrayList<>();

//        2.判断输入合法性
            String telephone = updateAccountVo.getTelephone();
            if (telephone != null && !telephone.isEmpty()){
                if (telephone.length() != 11 || telephone.charAt(0) != '1') {
                    return Result.error("请检查输入手机号是否有误");
                }
            }
            if (updateAccountVo.getName() == null || updateAccountVo.getName().equals(" ")) {
                return Result.error("姓名不能为空！");
            }
            if (telephone.equals(user.getTelephone())){
                user1.setTelephone(null);
            }
            if (updateAccountVo.getName().equals(user.getName())){
                user1.setName(null);
            }
            if (updateAccountVo.getState()==user.getState()){
                user1.setState(null);
            }
//        3.user1设置
            user1.setTelephone(updateAccountVo.getTelephone());
            user1.setName(updateAccountVo.getName());
            user1.setState(updateAccountVo.getState());
            user1.setOrganizationid(updateAccountVo.getOrganizationid());
            user1.setId(updateAccountVo.getId());

            User userId = userService.findUserId(user1);
            if (userId != null && !(userId.getId().equals(user1.getId())) ){
                System.out.println(userId.getId() != user1.getId());
                System.out.println();
                System.out.println(userId);
                System.out.println(userId.getId());
                System.out.println(user1.getId());
                return Result.error("该手机号已在系统存在");

            }

//        7.判断传入角色是否系统拥有
            List<String> integers = roleService.selectRolesByIds(updateAccountVo.getRoleid());
            if (integers.size() < updateAccountVo.getRoleid().length) {
                return Result.error("传入数据中，有角色信息不存在");
            }
            userRoleService.stopUseRole(updateAccountVo.getId());
//        8.修改用户
            int i = userService.updateUser(user1);
            if (i > 0) {
                log.info("账号更新成功");
//                9.根据用户id停用了所有的角色信息后，重新加入角色关系信息
                for (int i2 = 0; i2 < updateAccountVo.getRoleid().length; i2++) {
                    UserRole userRole1 = new UserRole();
                    userRole1.setUserid(user1.getId());
                    userRole1.setRoleid(updateAccountVo.getRoleid()[i2]);
                    userRole1.setState(1);
                    userRole.add(i2, userRole1);
                }
                int i1 = userRoleService.saveUserRole(userRole);
                if (i1 > 0) {
                    log.info("用户更新成功");
                    return Result.success("用户更新成功");
                } else {
                    log.info("用户更新成功");
                    return Result.error("用户更新成功");
                }
            }
        }
        return Result.error();
    }
    /**
     * 管辖项目（树形结构展示公司内容，用鲁雨鑫的接口）
     */
    @PostMapping("/manageProject")
    @ApiOperation(value = "管辖项目")
    @Transactional
    public Result manageProject(@RequestBody ManageProjectVo manageProjectVo){
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
//        User principal = (User) authentication.getPrincipal();
//        Integer organizationid =manageProjectVo.getOrganizationid();
        Integer id = manageProjectVo.getUserid();

        int[] ints = userService.FindUserIds(manageProjectVo.getAccount());
        if (ints.length==1){
             manageProjectService.stopUse(manageProjectVo.getAccount());
                List<ManageProject> list = new ArrayList<>();
                int[] developmentIds = manageProjectVo.getDevelopmentIds();
                for (int i = 0; i < developmentIds.length; i++) {
                    ManageProject manageProject = new ManageProject();
                    manageProject.setAccount(manageProjectVo.getAccount());
                    manageProject.setState(1);
                    manageProject.setDevelopmentid(developmentIds[i]);
                    list.add(i,manageProject);
                }

                int i = manageProjectService.saveManageProject(list);
                if (i==0){
                    return  Result.error("操作管辖项目失败");
                }else {
                    departmentTreeUtils.updateDepartmentTree(id);
                    return Result.success("操作管辖项目成功");
                }
        }else {
            return Result.error("请检查传入的账号是否正确！");
        }

    }
    /**
     * 树形结构展示
     */
    @PostMapping("/tree")
    @ApiOperation(value = "管辖项目的树形展示")
    public Result tree(@RequestParam("userId")Integer id,@RequestParam("organizationId")Integer organizationid ){
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser principal = (LoginUser) authentication.getPrincipal();
        User user = principal.getUser();
//        Integer organizationid = user.getOrganizationid();
//        Integer id = user.getId();
        List<TreeNode> treeNodes = DepartmentTree.buildUserDepartmentTree(id, organizationid, iOrganizationVOService.findAll(), iProjectVOService.findAll(),
                iBuildingUnitsVOService.findAll(), iLayerVOService.findAll(), iRoomVOService.findAll());
        List<TreeNode>  list = ProjectRemoveNode.removeNodes(treeNodes);
//        System.out.println(list.get(0));
        log.info(String.valueOf(list.get(0)));
        TreeNode treeNode = DepartmentTree.removeDisabledNodes(list.get(0));
        return Result.success(Collections.singletonList(treeNode));
    }
}
